import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'
const request = axios.create({
  // 开发环境使用：'/api'
  // 生产环境使用 '/prop-api'
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000 }
)
request.interceptors.request.use(config => {
  const token = store.state.user.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, error => Promise.reject(error)
)
request.interceptors.response.use(response => {
  if (response.data instanceof Blob) { return response.data } else if (response.data.success) { return response.data } else {
    Message.error(response.data.message)
    return Promise.reject(response.data.message)
  }
}, async error => {
  if (error.status === 401) {
    Message({ type: 'warning', message: 'token过期' })
    await store.dispatch('user/logout')
    router.push('/login')
    return Promise.reject(error)
  }
  Message.error(error.message)
  return Promise.reject(error)
}

)
export default request
